package com.hyt.it.ogt.ks.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.it.ogt.dict.model.entity.Dict;
import com.hyt.it.ogt.dict.service.IDictService;
import com.hyt.it.ogt.ks.enums.BizStatusCode;
import com.hyt.it.ogt.ks.enums.ExamConfigCode;
import com.hyt.it.ogt.ks.feign.KwClient;
import com.hyt.it.ogt.ks.feign.model.CandidatePaperInfo;
import com.hyt.it.ogt.ks.feign.model.Exam;
import com.hyt.it.ogt.ks.feign.model.ExamDTO;
import com.hyt.it.ogt.ks.feign.model.ItemDataVO;
import com.hyt.it.ogt.ks.feign.model.PaperDataVO;
import com.hyt.it.ogt.ks.feign.model.TopicDataVO;
import com.hyt.it.ogt.ks.model.vo.ExamConfigVO;
import com.hyt.it.ogt.ks.model.vo.SkinVO;
import com.hyt.it.ogt.ks.model.vo.paper.PItemDTO;
import com.hyt.it.ogt.ks.model.vo.paper.POptionDTO;
import com.hyt.it.ogt.ks.model.vo.paper.PTopicDTO;
import com.hyt.it.ogt.ks.service.ExamInfoCacheService;
import com.hyt.it.ogt.ks.service.IExamCacheService;
import com.hyt.it.ogt.ks.util.Constants;
import com.hyt.it.ogt.ks.util.EnCacheUtil;
import com.hyt.it.ogt.ks.util.KeyDefineCommon;
import com.hyt.loginfo.enums.SysSkinSettingCodeEnum;
import com.hyt.loginfo.model.Skin;
import com.hyt.loginfo.service.ISystemSkinService;
import com.hyt.loginfo.service.IUaDeptService;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ExamCacheServiceImpl implements IExamCacheService {
    @Resource
    private KwClient kwClient;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private EnCacheUtil enCacheUtil;
    @Resource
    private IDictService dictService;
    @Resource
    private ExamInfoCacheService examInfoCacheService;
    @Resource
    private ISystemSkinService iSystemSkinService;
    @Resource
    private IUaDeptService iUaDeptService;

    /**
     * 考试项目配置信息
     * @param examId
     * @return
     */
    @Override
    public List<ExamConfigVO> getExamConfigCache(String examId) {
        String repRtn = kwClient.getExamConfig(examId);
        ApiResponse<JSONArray> res = JSON.parseObject(repRtn, ApiResponse.class);
        if (res.getCode().intValue() != BizStatusCode.KW_SUCCESS_OK.getCode().intValue()) {
            //考生未从题库模块获取到试卷信息
            return null;
        }else{
            List<ExamConfigVO> list = JSON.parseArray(res.getData().toJSONString(), ExamConfigVO.class);
            return list;
        }
    }

    /**
     * 是否练习模式
     * @param examId
     * @return
     */
    @SneakyThrows
    @Override
    public boolean isPracticeMode (String examId) {
        List<ExamConfigVO> examConfigVOList =  getExamConfigCache(examId);
        return examConfigVOList.stream().parallel().anyMatch(examConfigVO -> ExamConfigCode.EXAM_CONFIG_CODE_PRACTICE_MODE.getCode().equalsIgnoreCase(examConfigVO.getConfigCode()) && "true".equalsIgnoreCase(examConfigVO.getConfigValue()));
    }

    /**
     * 是否统一开考，统一结束
     * @param examId
     * @return
     */
    @SneakyThrows
    @Override
    public boolean isUnifiedStartEnd (String examId) {
        List<ExamConfigVO> examConfigVOList =  getExamConfigCache(examId);
        return examConfigVOList.stream().parallel().anyMatch(examConfigVO ->
                ExamConfigCode.EXAM_CONFIG_CODE_UNIFIED_START_END.getCode().equalsIgnoreCase(examConfigVO.getConfigCode())
                        && "true".equalsIgnoreCase(examConfigVO.getConfigValue()));
    }

    /**
     * 获取时间的毫秒数
     * @param examId
     * @return
     */
    @Override
    public Long getPaperEndDateMilli(String examId) {
        ExamDTO examDTO = examInfoCacheService.getExamInfoFromCache(examId);
        Exam exam = examDTO.getExam();
        return exam.getEndDate().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    @Override
    @SneakyThrows
    public CandidatePaperInfo getNewestPaperInfo(String examId, String candidateId) {
        String key = KeyDefineCommon.getCandidateCacheCandidatePaperInfo(candidateId);
        String kwPaperInfo = kwClient.getExamPaperInfo(examId,candidateId);
        ApiResponse<CandidatePaperInfo> kwPaperInfoResponse = ApiResponse.ConvertRet(kwPaperInfo, CandidatePaperInfo.class);
        if (kwPaperInfoResponse.getCode().intValue() != BizStatusCode.KW_SUCCESS_OK.getCode().intValue()) {
            //未从考务获取到考生试卷信息
            return null;
        }
        //将从考务获取到的信息放入缓存，返回前端数据使用
        CandidatePaperInfo candidatePaperInfo = kwPaperInfoResponse.getData();
        //写缓存
        redisTemplate.opsForValue().set(key, JSON.toJSONString(candidatePaperInfo), 24, TimeUnit.HOURS);
        //获取了新的试卷清除之前的二级缓存
        enCacheUtil.putAndSetPaperInfoCache(key,JSON.toJSONString(candidatePaperInfo));
        return candidatePaperInfo;
    }

    @Override
    @SneakyThrows
    public CandidatePaperInfo getCandidatePaperInfoCache(String examId, String candidateId) {
        String key = KeyDefineCommon.getCandidateCacheCandidatePaperInfo(candidateId);
        //读缓存
        //String candidatePaperInfoString = (String) redisTemplate.opsForValue().get(key);
        String candidatePaperInfoString = enCacheUtil.getPaperInfoCache(key);
        if (StringUtils.isNotBlank(candidatePaperInfoString) && !"null".equalsIgnoreCase(candidatePaperInfoString)) {
                CandidatePaperInfo candidatePaperInfo = JSON.parseObject(candidatePaperInfoString, CandidatePaperInfo.class);
                log.info("考生随机抽到的试卷：{}、{}、{}", examId, candidateId, candidatePaperInfoString);
                return candidatePaperInfo;
            }
        String kwPaperInfo = kwClient.getCandidatePaperInfo(candidateId);
        ApiResponse<CandidatePaperInfo> kwPaperInfoResponse = ApiResponse.ConvertRet(kwPaperInfo, CandidatePaperInfo.class);
        if (kwPaperInfoResponse.getCode().intValue() != BizStatusCode.KW_SUCCESS_OK.getCode().intValue()) {
            //未从考务获取到考生试卷信息
            return null;
        }
        //将从考务获取到的信息放入缓存，返回前端数据使用
        CandidatePaperInfo candidatePaperInfo = kwPaperInfoResponse.getData();
        //写缓存
        redisTemplate.opsForValue().set(key, JSON.toJSONString(candidatePaperInfo), 24, TimeUnit.HOURS);
        enCacheUtil.putPaperInfoCache(key,JSON.toJSONString(candidatePaperInfo),null);
        return candidatePaperInfo;
    }

    @Override
    public PItemDTO getPaperItemFromCache(String paperId, String paperVersion, String itemId) {
        String key = KeyDefineCommon.getPaperItemKey(paperId, paperVersion);// todo 先去encache里边取
        PItemDTO obj = (PItemDTO) redisTemplate.opsForHash().get(key, itemId);
        if (obj == null) {
            this.setPaperItemToCache(paperId, paperVersion);
            obj = (PItemDTO) redisTemplate.opsForHash().get(key, itemId);
        }
        return obj;
    }

    @Override
    public PTopicDTO getPaperTopicFromCache(String paperId, String paperVersion, String topicId) {
        String key = KeyDefineCommon.getPaperTopicKey(paperId, paperVersion);
        Object obj = redisTemplate.opsForHash().get(key, topicId);
        if (obj == null) {
            this.setPaperItemToCache(paperId, paperVersion);
            obj = redisTemplate.opsForHash().get(key, topicId);
        }
        return (PTopicDTO) obj;
    }

    @Override
    public Map<String, PTopicDTO> getPaperTopicListFromCache(String paperId, String paperVersion) {
        String topicKey = KeyDefineCommon.getPaperTopicKey(paperId, paperVersion);
        //Map<String, PTopicDTO> map = redisTemplate.opsForHash().entries(topicKey);
        Map<String,PTopicDTO> map = enCacheUtil.getPaperTopiCache(topicKey);
        if (map == null || map.isEmpty()) {
            this.setPaperItemToCache(paperId, paperVersion);
            map = redisTemplate.opsForHash().entries(topicKey);
        }
        return map;
    }

    @Override
    public Map<String, PItemDTO> getPaperItemByTopicId(String paperId, String paperVersion, String topicId) {
        String itemKey = KeyDefineCommon.getPaperItemKey(paperId, paperVersion);
        //Map<String, PItemDTO> map = redisTemplate.opsForHash().entries(itemKey);
        Map<String,PItemDTO> map = enCacheUtil.getPaperItemCache(itemKey);
        if (map == null || map.isEmpty()) {
            this.setPaperItemToCache(paperId, paperVersion);
            map = redisTemplate.opsForHash().entries(itemKey);
        }
        return this.filterItem(map, topicId);
    }

    private Map<String, PItemDTO> filterItem(Map<String, PItemDTO> map, String topicId){
        if (map == null || map.isEmpty()) {
            return null;
        } else {
            Map<String, PItemDTO> itemDTOMap = new HashMap<>();
            map.forEach((k, v) -> {
                if(v.getTopicId().equalsIgnoreCase(topicId)) {
                    itemDTOMap.put(k, v);
                }
            });
            return itemDTOMap;
        }
    }

    public void setPaperItemToCache(String paperId, String paperVersion) {
        String paperKey = KeyDefineCommon.getPaperItemKey(paperId, paperVersion);
        String topicKey = KeyDefineCommon.getPaperTopicKey(paperId, paperVersion);
        Long size = redisTemplate.opsForHash().size(paperKey);
        if (size == null || size.longValue() == 0) {
            synchronized (this) {
                if (redisTemplate.opsForHash().size(paperKey) > 0) {
                    return;
                }
                PaperDataVO paper = this.getPaperInfoCache(paperId, paperVersion);
                if (paper != null) {
                    // 小题新星
                    Map<String, PItemDTO> itemMap = new HashMap<>();
                    // 大题下新星
                    Map<String, PTopicDTO> topicMap = new HashMap<>();
                    // 大题ID和大题数量映射
                    Map<String, Integer> itemNumberMap = new HashMap<>();
                    paper.getTopicDataList().stream().forEach(topic -> {
                        topicMap.put(topic.getTopicId(), this.createTopic(topic));
                        itemNumberMap.put(topic.getTopicId(), topic.getItemDataList().size());
                        topic.getItemDataList().stream().forEach(item -> {

                            PItemDTO pItem = this.createItem(item, topic);

                            if(item.getChildItemList().size() > 0){
                                Map<String, PItemDTO> childItemMap = new HashMap<>();
                                item.getChildItemList().stream().forEach(childItem -> {

                                    PItemDTO cItem = this.createItem(childItem, topic);

                                    childItemMap.put(cItem.getItemId(), cItem);
                                });

                                pItem.setChildItemMap(childItemMap);

                            }
                            itemMap.put(pItem.getItemId(), pItem);
                        });
                    });
                    // 小题信息
                    redisTemplate.opsForHash().putAll(paperKey, itemMap);
                    redisTemplate.expire(paperKey, Constants.time, Constants.timeUnit);
                    enCacheUtil.putPaperTopicItemCache(paperKey, JSON.toJSONString(itemMap),null);
                    // 大题信息
                    redisTemplate.opsForHash().putAll(topicKey, topicMap);
                    redisTemplate.expire(topicKey, Constants.time, Constants.timeUnit);
                    enCacheUtil.putPaperTopicItemCache(topicKey, JSON.toJSONString(topicMap),null);

                    /*// 题数量缓存
                    String itemNumberKey = KeyDefineCommon.getItemNumberByTopicIdKey(paperId, paperVersion);
                    redisTemplate.opsForHash().putAll(itemNumberKey, itemNumberMap);
                    redisTemplate.expire(itemNumberKey, Constants.time, Constants.timeUnit);
                    enCacheUtil.putPaperTopicItemCache(itemNumberKey, JSON.toJSONString(itemNumberMap),null);*/
                }
            }
        }
    }



    private PTopicDTO createTopic(TopicDataVO topicDataVO){
        return PTopicDTO.builder().topicDescription(topicDataVO.getTopicDescription()).topicId(topicDataVO.getTopicId())
                .topicName(topicDataVO.getTopicName()).topicScore(topicDataVO.getTopicScore())
                .itemNumber(topicDataVO.getItemDataList().size()).topicSort(topicDataVO.getTopicSort()).build();
    }

    private PItemDTO createItem(ItemDataVO itemDataVO, TopicDataVO topic){
        Map<String, POptionDTO> optionMap = new HashMap<>();
        if(Objects.nonNull(itemDataVO.getOptionsDataList()) && itemDataVO.getOptionsDataList().size() > 0){
            itemDataVO.getOptionsDataList().stream().forEach(option -> {
                optionMap.put(option.getOptionId(),
                        POptionDTO.builder()
                                .optionContent(option.getOptionContent())
                                .optionId(option.getOptionId())
                                .optionScore(option.getScore())
                                .optionSort(option.getOptionSort())
                                .optionName(option.getOptionName())
                                .optionAttrs(option.getOptionAttrs())
                                .build()
                );
            });
        }
        return PItemDTO.builder()
                .itemId(itemDataVO.getItemId())
                .itemContent(itemDataVO.getItemContent())
                .itemDescription(itemDataVO.getDescription())
                .itemPid(itemDataVO.getItemPid())
                .standardAnswer(itemDataVO.getAnswer())
                .itemNumber(topic.getItemDataList().size())
                .itemType(itemDataVO.getItemType())
                .optionMap(optionMap)
                .topicName(topic.getTopicName())
                .topicId(topic.getTopicId())
                .topicScore(topic.getTopicScore())
                .topicSort(topic.getTopicSort())
                .topicDescription(topic.getTopicDescription())
                .itemSort(itemDataVO.getItemSort())
                .stemAttrs(itemDataVO.getStemAttrs())
                .answerAttrs(itemDataVO.getAnswerAttrs())
                .descriptionAttrs(itemDataVO.getDescriptionAttrs())
                .attrsDataList(itemDataVO.getAttrsDataList())
                .score(itemDataVO.getScore())
                .outTimeSecond(NumberUtils.toLong(String.valueOf(itemDataVO.getOutTimeSecond()),0L))
                .openItemTiming(itemDataVO.getOpenItemTiming())
                .build();
    }

    @Override
    @SneakyThrows
    public PaperDataVO getPaperInfoCache(String paperId, String paperVersion) {
        if(StringUtils.isBlank(paperId) || StringUtils.isBlank(paperVersion)){
            return null;
        }
        //读缓存
        String key = KeyDefineCommon.getPaperInfoKey(paperId, paperVersion);
        //String paperInfoString = (String) redisTemplate.opsForValue().get(key);
        String paperInfoString = enCacheUtil.getPaperInfoCache(key);
        if (StringUtils.isNotBlank(paperInfoString) && !"null".equalsIgnoreCase(paperInfoString)) {
            PaperDataVO paperDataVO = JSON.parseObject(paperInfoString, PaperDataVO.class);
            return paperDataVO;
        }

        String res = kwClient.getPaperData(paperId, paperVersion);
        log.debug("从题库获取试卷返回结果：{}", res);
        ApiResponse<PaperDataVO> tkPaperInfoResponse = ApiResponse.ConvertRet(res, PaperDataVO.class);
        if (tkPaperInfoResponse.getCode().intValue() != BizStatusCode.KW_SUCCESS_OK.getCode().intValue()) {
            //考生未从题库模块获取到试卷信息
            return null;
        }
        PaperDataVO paperDataVO = tkPaperInfoResponse.getData();
        //写缓存
        redisTemplate.opsForValue().set(key, JSON.toJSONString(paperDataVO), 24, TimeUnit.HOURS);
        enCacheUtil.putPaperInfoCache(key,JSON.toJSONString(paperDataVO),null);
        return paperDataVO;
    }

    /**
     * 获取试卷信息 -- 无题干/描述  选项无描述信息
     * @param paperId
     * @param paperVersion
     * @return
     */
    @Override
    @SneakyThrows
    public PaperDataVO getPaperInfoSimpleCache(String paperId, String paperVersion){
        if(StringUtils.isBlank(paperId) || StringUtils.isBlank(paperVersion)){
            return null;
        }
        //读缓存
        String key = KeyDefineCommon.getPaperInfoSImpleKey(paperId, paperVersion);
        //String paperInfoString = (String) redisTemplate.opsForValue().get(key);
        String paperInfoString = enCacheUtil.getPaperInfoCache(key);
        if (StringUtils.isNotBlank(paperInfoString) && !"null".equalsIgnoreCase(paperInfoString)) {
            PaperDataVO paperDataVO = JSON.parseObject(paperInfoString, PaperDataVO.class);
            return paperDataVO;
        }
        String res = kwClient.getPaperDataSimple(paperId, paperVersion);
        log.debug("从题库获取试卷返回结果：{}", res);
        ApiResponse<PaperDataVO> tkPaperInfoResponse = ApiResponse.ConvertRet(res, PaperDataVO.class);
        if (tkPaperInfoResponse.getCode().intValue() != BizStatusCode.KW_SUCCESS_OK.getCode().intValue()) {
            //考生未从题库模块获取到试卷信息
            return null;
        }
        PaperDataVO paperDataVO = tkPaperInfoResponse.getData();
        //写缓存
        redisTemplate.opsForValue().set(key, JSON.toJSONString(paperDataVO), 24, TimeUnit.HOURS);
        enCacheUtil.putPaperInfoCache(key,JSON.toJSONString(paperDataVO),null);
        return paperDataVO;
    }

    /**
     * 获取项目发布状态
     * @param examId
     * @return
     */
    @Override
    public Boolean getPublishExam(String examId) {
        ExamDTO examDTO = examInfoCacheService.getExamInfoFromCache(examId);
        return examDTO.getExam().getPublishExam();
    }

    @Override
    public Boolean checkExamFinishOrNotPublish(String examId) {
        ExamDTO examDTO = examInfoCacheService.getExamInfoFromCache(examId);
        if(!examDTO.getExam().getPublishExam()
                || LocalDateTime.now().isBefore(examDTO.getExam().getBeginDate())
                || LocalDateTime.now().isAfter(examDTO.getExam().getEndDate())) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Integer getItemNumberByTopicId(String paperId, String paperVersion, String topicId) {
        String key = KeyDefineCommon.getItemNumberByTopicIdKey(paperId, paperVersion);
        Object obj = redisTemplate.opsForHash().get(key, topicId);
        if (obj == null) {
            this.setPaperItemToCache(paperId, paperVersion);
            obj = redisTemplate.opsForHash().get(key, topicId);
        }
        return obj == null ? null : Integer.valueOf(obj.toString());
    }


    /**
     * 从缓存中读取机构下考试的皮肤
     * @param projectId
     * @return
     */
    @Override
    public SkinVO getProjectSkin(String projectId){
        String skinKey = KeyDefineCommon.getProjectExamSkinKey(projectId);
        String obj = String.valueOf(redisTemplate.opsForValue().get(skinKey));
        if(StringUtils.isBlank(obj) || Objects.equals("null",obj)){
            return putToCache(projectId,skinKey);
        }
        return JSON.parseObject(obj,SkinVO.class);
    }

    private SkinVO putToCache(String projectId,String key){
        //String resSkinRtn = iUaDeptService.getSkinByOfficeidAndSysCode.skin(projectId, "ks");
        Skin skin = iSystemSkinService.getSkinByOfficeidAndSysCode(projectId, SysSkinSettingCodeEnum.KS);
        SkinVO skinVO = new SkinVO();
        skinVO.setBackground(skin.getBackground());
        skinVO.setLogo(skin.getLogo())     ;
        redisTemplate.opsForValue().set(key,JSON.toJSONString(skinVO, SerializerFeature.WriteNullStringAsEmpty),5,TimeUnit.MINUTES);
        return skinVO;
    }

    /**
     * 从缓存中读取机构下考试的皮肤
     * @param officeId
     * @return
     */
    @Override
    public String getProjectName(String officeId){
        String nameKey = KeyDefineCommon.getProjectNameKey(officeId);
        String obj = String.valueOf(redisTemplate.opsForValue().get(nameKey));
        if(StringUtils.isBlank(obj) || Objects.equals("null",obj)){
            return projectNamePutoCache(officeId,nameKey);
        }
        return obj;
    }

    private String projectNamePutoCache(String officeId,String key){
        String skin = iUaDeptService.queryOrgNameById(officeId);
        redisTemplate.opsForValue().set(key,skin,5,TimeUnit.MINUTES);
        return skin;
    }



    @Override
    public String getPaperTranslateCache(String paperId, String paperVersion, String id, String language) {
        String paperKey = KeyDefineCommon.getPaperTranslateKey(paperId, paperVersion, language);
        HashMap<String, String> cacheMap = enCacheUtil.getPaperTranslateCache(paperKey);
        if(Objects.isNull(cacheMap)){
            return this.putPaperTranslateCache(paperId,paperVersion,language,id);
        }
        return cacheMap.get(id);
    }

    @Override
    public void putTranslateToCache(String paperId, String paperVersion, String language) {
        String paperKey = KeyDefineCommon.getPaperTranslateKey(paperId, paperVersion, language);
        redisTemplate.delete(paperKey);
        ApiResponse<Map<String, String>> apiResponse = kwClient.getPaperTranslate(language, paperId, paperVersion);
        if(apiResponse.getData() != null) {
            redisTemplate.opsForValue().set(paperKey, JSON.toJSONString(apiResponse.getData()));
            redisTemplate.expire(paperKey, 5, TimeUnit.HOURS);
        }
    }

    /**
     * 放入缓存encache
     * @return
     */
    public String putPaperTranslateCache(String paperId, String paperVersion, String language, String id) {
        String paperKey = KeyDefineCommon.getPaperTranslateKey(paperId, paperVersion, language);
        try {
            //先去redis中获取
            Object dataStr = redisTemplate.opsForValue().get(paperKey);
            if (dataStr != null) {
                HashMap<String, String> data = JSON.parseObject(dataStr.toString(), new TypeReference<HashMap<String, String>>() {});
                if (Objects.nonNull(data)) {
                    enCacheUtil.putPaperTransateToEncache(paperKey, JSON.toJSONString(data));
                    return data.get(id);
                }
            }
            //redis中没有则要去kw里边取
            redisTemplate.delete(paperKey);
            ApiResponse<Map<String, String>> apiResponse = kwClient.getPaperTranslate(language, paperId, paperVersion);
            if (apiResponse.getData() != null && !apiResponse.getData().isEmpty()) {
                redisTemplate.opsForValue().set(paperKey, JSON.toJSONString(apiResponse.getData()));
                redisTemplate.expire(paperKey, 5, TimeUnit.HOURS);
                enCacheUtil.putPaperTransateToEncache(paperKey, JSON.toJSONString(apiResponse.getData()));
            }
            return apiResponse.getData().get(id);
        } catch (Exception e) {
            log.error("数据存入ehcache缓存失败，key:【{}】,数据为:【{}】异常信息为:【{}】", paperId, new Object(), e);
            return null;
        }
    }

    /**
     * 手动清理encache翻译试卷的缓存
     * @param paperId
     * @param paperVersion
     * @param language
     */
    @Override
    public void clearPaperTransalteEncache(String paperId,String paperVersion,String language){
        String paperKey = KeyDefineCommon.getPaperTranslateKey(paperId, paperVersion, language);
        enCacheUtil.clearPaperTransateFromEncache(paperKey);
    }

    /**
     * 手动触发清理encache里的paperInfo的缓存
     * @param pwd
     * @return
     */
    public Boolean clearPaperInfoEncache(String pwd){
        try {
            Dict dict = dictService.getByType(Constants.EHCACHE_CLEAR_PWD).get(0);
            String dictPwd = dict.getLabel();
            if(!pwd.equalsIgnoreCase(dictPwd)){
                return Boolean.FALSE;
            }
            enCacheUtil.clearPaperInfoCache();
            return Boolean.TRUE;
        } catch (Exception e){
            log.error("手动清理ehcache二级试卷信息缓存失败：",e);
            return Boolean.FALSE;
        }
    }

    /**
     * 手动触发清理redis 中机构的皮肤缓存
     * @param pwd
     * @param examId
     * @return
     */
    public Boolean clearProjectSkinRedisCache(String pwd, String examId){
        try {
            Dict dict = dictService.getByType(Constants.EHCACHE_CLEAR_PWD).get(0);
            String dictPwd = dict.getLabel();
            if(!pwd.equalsIgnoreCase(dictPwd)){
                return Boolean.FALSE;
            }
            ExamDTO examDTO = examInfoCacheService.getExamInfoFromCache(examId);
            if(Objects.isNull(examDTO)){
                return Boolean.FALSE;
            }
            Exam exam = examDTO.getExam();
            String nameKey = KeyDefineCommon.getProjectNameKey(exam.getOfficeId());
            String skinKey = KeyDefineCommon.getProjectExamSkinKey(exam.getOfficeId());
            redisTemplate.delete(nameKey);
            redisTemplate.delete(skinKey);
            return Boolean.TRUE;
        } catch (Exception e){
            log.error("手动清理ehcache二级试卷信息缓存失败：",e);
            return Boolean.FALSE;
        }
    }
}
